
import java.io.*;
import java.io.BufferedReader;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * Servlet faisant office d'intermédiaire HTTP : émet une requête
 * vers l'url passée en paramètre, et renvoie le résultat. Permet aux pages
 * provenant du serveur d'émettre des appels Ajax vers d'autres serveurs,
 * en passant par le serveur courant, comme les restrictions de sécurité
 * des navigateurs y obligent.
 */
public class ProxyAction extends HttpServlet {

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Supprimer les en-tetes de la reponse
        response.reset();
        response.setContentType("text/xml; charset=UTF-8");
        PrintWriter out = response.getWriter();
        String url = request.getParameter("url");
        System.out.println("URL : " + url);
        ClientResource resource = new ClientResource(url);

        // Send an authenticated request using the Basic authentication
        // scheme.
        //resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "herp", "derp");

        try {
            Representation representation = resource.get();
            representation.write(out);
        } catch (ResourceException exc) {
            Status expStatus = Status.CLIENT_ERROR_NOT_FOUND;
        } finally {
            out.close();
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Supprimer les en-tetes de la reponse
        response.reset();
        response.setContentType("text/xml; charset=UTF-8");
        PrintWriter out = response.getWriter();
        String url = request.getParameter("url");
        System.out.println("URL : " + url);
        ClientResource resource = new ClientResource(url);
        try {
            BufferedReader in = request.getReader();
            DocumentBuilder parser;
            parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = parser.parse(new InputSource(new StringReader(in.readLine())));
            Representation representation = resource.post(document);
            representation.write(out);
        } catch (ResourceException exc) {
            Status expStatus = Status.CLIENT_ERROR_NOT_FOUND;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ProxyAction.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(ProxyAction.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    /**
     * Handles the HTTP <code>PUT</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Supprimer les en-tetes de la reponse
        response.reset();
        response.setContentType("text/xml; charset=UTF-8");
        PrintWriter out = response.getWriter();
        String url = request.getParameter("url");
        System.out.println("URL : " + url);
        ClientResource resource = new ClientResource(url);
        try {
            //PENSER A RECUPERER CE QUIL FAUT POST
            BufferedReader in = request.getReader();
            DocumentBuilder parser;
            parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = parser.parse(new InputSource(new StringReader(in.readLine())));
            Representation representation = resource.put(document);
            representation.write(out);
        } catch (ResourceException exc) {
            Status expStatus = Status.CLIENT_ERROR_NOT_FOUND;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ProxyAction.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(ProxyAction.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    /**
     * Handles the HTTP <code>DELETE</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Supprimer les en-tetes de la reponse
        response.reset();
        response.setContentType("text/xml; charset=UTF-8");
        PrintWriter out = response.getWriter();
        String url = request.getParameter("url");
        System.out.println("URL : " + url);
        ClientResource resource = new ClientResource(url);


        try {
            Representation representation = resource.delete();
            representation.write(out);
        } catch (ResourceException exc) {
            Status expStatus = Status.CLIENT_ERROR_NOT_FOUND;
        } finally {
            out.close();
        }
    }

    /**
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
// </editor-fold>
}
